package com.maotai.llzhou.timetask;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.thread.MaotaiUpdateAddressThread;
import com.maotai.llzhou.thread.MaotaiYuYueThread;
import com.maotai.llzhou.util.IPFactory;
import com.maotai.llzhou.util.JSUtil;

/**
 * 登录并且抢购
 */
public class MaotaiUpdateAddressTask {

	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;

	public void beginTask() {
		List<Map<String, Object>> list;
		List<Map<String, Object>> addressList;
		try {
			list = maotaiService.getZhanghaoUpdateAddress();
			addressList = maotaiService.getAddressLibrary();
			if (list != null && list.size() > 0) {
				JSONArray jArray = IPFactory.getIpAndPort();
				int count = list.size();
				if(jArray.size()<count){
					count=jArray.size();
				}
				if(addressList.size()<count){
					count=addressList.size();
				}
				for(int i=0;i<count;i++){
					Map<String, Object> zhanghao = list.get(i);
					Map<String, Object> addrMap = addressList.get(i);
					JSONObject jj = (JSONObject)jArray.get(i);
					String ipAndPort = jj.getString("ip")+":"+jj.getString("port");
					zhanghao.put("yuyuestatus", "9");
					maotaiService.updateZhanghaoYuYueStatus(zhanghao);
					addrMap.put("usestatus", "1");
					maotaiService.updateAddressLibraryStatus(addrMap);
					MaotaiWebCookie mwc = new MaotaiWebCookie();
					String kcross = zhanghao.get("kcross")+"";
					String acw_tc = zhanghao.get("acw_tc")+"";
					String csrfToken = zhanghao.get("csrfToken")+"";
					mwc.setKcross(kcross);
					mwc.setAcw_tc(acw_tc);
					mwc.setCsrfToken(csrfToken);
					String auth = zhanghao.get("auth")+"";
					mwc.setAuth(auth);
					String timestamp = System.currentTimeMillis()+"";
					String sign = JSUtil.excuFunctionA(mwc.getAuth()+timestamp);
					mwc.setSign(sign);
					mwc.setTimestamp(timestamp);
					MaotaiUpdateAddressThread myyt = new MaotaiUpdateAddressThread(maotaiService,zhanghao,ipAndPort,mwc,addrMap);
					myyt.start();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
